package com.yc.thread;

//生产者与消费者模式

import java.util.ArrayList;
import java.util.List;

public class Demo4 {

    // 仓库
    List<Object> store = new ArrayList<>();

    // 生产
    synchronized void produce() throws InterruptedException {
        int num = 0;
        while (true) {
            while(store.isEmpty()){
                for (int i = 0; i < 10; i++) {
                    Object o = "商品" + ++num;
                    store.add(o);
                    System.out.println("生产: " + o);
                    Thread.sleep(100);
                }
            }
            // 通知其他线程
            this.notifyAll();
            // 在此等待消费者消费完商品
            this.wait();

        }
    }

    // 消费
    void consume() throws InterruptedException {
        String name = Thread.currentThread().getName();
        a : while (true) {
            synchronized (this) {
                while (store.isEmpty() == false) {
                    Object o = store.remove(0);
                    System.out.println(name + "消费: " + o);
                    Thread.sleep(300);
                    continue a;
                }
               // 通知其他线程
                this.notifyAll();
                // 在此等待生产者生产商品
                this.wait();
            }
        }
    }

    public static void main(String[] args) {
        Demo4 demo4 = new Demo4();

        Thread t1 = new Thread(() -> {
            try {
                demo4.produce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t1.start();

        for (int i = 0; i < 10; i++) {
            Thread t2 = new Thread(() -> {
                try {
                    demo4.consume();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, "消费者" + (i + 1));
            t2.start();
        }


    }


}
